import 'dart:async';

import 'package:ez_ic_led/home/custom_view.dart';
import 'package:ez_ic_led/home/mode_view.dart';
import 'package:ez_ic_led/home/voice_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:flutter_kit_vibrator/flutter_kit_vibrator.dart';

import '../bluetooth/send_data.dart';
import '../chooseColor/choose_color.dart';
import '../search/search_view.dart';
import '../tool/assets.dart';
import 'color_view.dart';

class MyHome extends StatefulWidget {
  const MyHome({super.key});

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  StreamSubscription<Map<BLEPeripheral, BluetoothConnectionState>>? _connectSubscription;
  List<int> color_select_list = [];
  double brightValue = 50;
  double speedValue = 50;
  int selectTypeIndex = 100;
  int selectModeIndex = 0;
  List<int> customColorList = [0xFF0000, 0x00FF00, 0x0000FF, 0, 0, 0, 0, 0, 0];
  List<int> showCustomColorList = [0xFF0000, 0x00FF00, 0x0000FF];
  @override
  void initState() {
    super.initState();
    listen();
    loadLocal();
  }

  @override
  void dispose() {
    super.dispose();
    _connectSubscription?.cancel();
  }

  void listen() {
    _connectSubscription ??= BluetoothManager.instance.connectionStateStream.listen((_) {
      setState(() => turn_on = true);
      SendData.send('RGB开关', turn_on);
      SendData.send('RGB排序', [(ledNum.intValue ~/ 3.0).toInt(), rgbIndex]);
    });
  }

  void loadLocal() async {
    rgbIndex = (await getString(rgbIndexKey) ?? '0').intValue;
    ledNum = await getString(ledNumKey) ?? '200';
  }

  Widget _btn(String icon, Function() onTap) {
    return IconButton(
        padding: const EdgeInsets.all(3),
        highlightColor: Colors.white.withOpacity(0.1),
        onPressed: onTap,
        icon: Image.asset(icon, fit: BoxFit.fill));
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕的宽度
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;
    GlobalConfig.scaleH = screenHeight / 667.0;

    // 设置状态栏背景颜色和图标颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏背景色
      statusBarIconBrightness: Brightness.light, // 状态栏图标颜色 (白色图标)
    ));

    return Scaffold(
      resizeToAvoidBottomInset: false, // 确保键盘弹出时，页面不自动调整大小
      appBar: null,
      body: Stack(
        children: [
          ///背景
          Positioned(
            child: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(image: AssetImage(assets.bg_view), fit: BoxFit.fitHeight),
              ),
            ),
          ),

          ///左按钮
          Positioned(
            left: 20,
            top: 50,
            width: 40,
            height: 40,
            child: _btn(turn_on ? assets.trun_on : assets.trun_off, () {
              setState(() => turn_on = !turn_on);
              SendData.send('RGB开关', turn_on);
            }),
          ),

          ///右按钮
          Positioned(
            right: 20,
            top: 50,
            width: 40,
            height: 40,
            child: Stack(
              children: [
                _btn(assets.setting, () {
                  SearchView search = SearchView(height: screenHeight - 70);
                  search.show(context, completion: () {});
                }),
                Center(
                  child: Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(4),
                        color: BluetoothManager.instance.connectedDeviceList.isNotEmpty
                            ? Color_btn_hight
                            : Colors.transparent),
                  ),
                ),
              ],
            ),
          ),

          ///
          Positioned(
              left: 0,
              right: 0,
              top: 80,
              bottom: 0,
              child: Column(
                children: [
                  ///色带
                  Flexible(
                      flex: 10,
                      child: ColorView(
                        color_select_list: color_select_list,
                        brightValue: brightValue,
                        speedValue: speedValue,
                        onChangedColor: (p0) {
                          mic_on = false;
                          color_select_list = p0;
                          SendData.send('RGB色盘', p0);
                          setState(() {});
                        },
                        onChangedBright: (p0) {
                          brightValue = p0;
                          SendData.send(mic_on ? '声控亮度' : '亮度', p0.toInt());
                          // setState(() {});
                        },
                        onChangedSpeed: (p0) {
                          speedValue = p0;
                          mic_on = false;
                          SendData.send('速度', p0.toInt());
                          setState(() => mic_on = false);
                        },
                      )),

                  ///model
                  Flexible(
                      flex: 2,
                      child: ModeView(onChanged: (p0) {
                        setState(() => mic_on = false);
                        SendData.send('RGB模式', p0 + 1);
                      })),
                  Flexible(
                      flex: 2,
                      child: CustomView(
                          selectType: selectTypeIndex,
                          selectModeIndex: selectModeIndex,
                          colorList: customColorList,
                          onChangedType: (p0) {
                            switch (p0) {
                              case 0:
                              case 2:
                                SendData.send('自定义方向', p0 == 0 ? 0 : 1);
                              case 1:
                                for (int i = 0; i < showCustomColorList.length; i++) {
                                  var rgb = showCustomColorList[i].bytes;
                                  rgb = rgb.padLeft(3);
                                  SendData.send('自定义换色', [i, rgb[0], rgb[1], rgb[2], showCustomColorList.length]);
                                }
                              case 3:
                                SendData.send('自定义循环', 0);
                              default:
                            }
                            selectTypeIndex = p0;
                            setState(() => mic_on = false);
                          },
                          onChangedMode: (p0) {
                            selectModeIndex = p0;
                            SendData.send('自定义模式', p0);
                            setState(() => mic_on = false);
                          },
                          onChangedColor: (p0, add) {
                            if (add) {
                              Navigator.push(
                                context,
                                MaterialPageRoute(builder: (context) {
                                  return ChooseColor(
                                      colorList: showCustomColorList,
                                      selectColorIndex:
                                          p0 > showCustomColorList.length - 1 ? showCustomColorList.length - 1 : p0,
                                      onChanged: (color, list) {
                                        setState(() {
                                          mic_on = false;
                                          customColorList[p0] = color;
                                        });
                                        showCustomColorList = list;
                                        var bytes = color.bytes;
                                        SendData.send('自定义颜色', [bytes[0], bytes[1], bytes[2], 0x01, p0]);
                                      });
                                }),
                              );
                            } else {
                              setState(() {
                                mic_on = false;
                                customColorList[p0] = 0;
                              });
                              SendData.send('自定义颜色', [0, 0, 0, 0x02, p0]);
                              FlutterKitVibrator.vibrate(duration: 100);
                            }
                          })),
                  Flexible(flex: 3, child: VoiceView()),
                ],
              )),
        ],
      ),
    );
  }
}
